package net.example.lesson6.concurrent;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
    public void test(final int nThread) throws InterruptedException {
        final CountDownLatch startLatch = new CountDownLatch(1);
        final CountDownLatch endLatch = new CountDownLatch(nThread);

        for (int i = 0; i < nThread; i++) {
            final int num = i;
            Thread t = new Thread(() -> {
                try {
                    System.out.println(String.format("线程%d等待主线程开始", num));
                    startLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    Thread.sleep(num * 1000);
                    System.out.println(String.format("执行子线程%d", num));
                    endLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

        Thread.sleep(3000);

        System.out.println("主线程启动完毕");
        startLatch.countDown();
        System.out.println("等待所有子线程执行完毕");
        endLatch.await();
        System.out.println("所有子线程执行完毕");

        System.out.println("主线程执行完毕");
    }


    public static void main(String[] args) {
        CountDownLatchTest test = new CountDownLatchTest();
        try {
            test.test(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
